import { url } from 'inspector';
import configEnv from '@/configEnv.js'
import storage from '@/common/utils/storage.js';

let BASEURL = configEnv.BASE_API_URL
let DEVURL = configEnv.DEV_API_URL

/*
* 全局请求封装
* @param path 请求路径
* @param method 请求类型(GET/POST/DELETE等)
* @oaram data 请求体数据
* @param loading 请求未完成是是否显示加载中，默认为true
*/
export default (path, method, data = {}) => {
	
	// 根据路径换域名
	if (path.startsWith('/dev-api') && 1 == 2){
		path = DEVURL + path
	}else{
		path = BASEURL + path
	}
	
	//把Token带入Header
	let token = storage.get("token");
	if (token != '' || token == null) {
		token = {"Authorization" : "Bearer " + token}
	} else {
		token = {}
	}
	
	// 文件上传OR普通请求
	if (method  == "FILE") {
		return uploadFile(path, data, token)
	}else{
		return request(path, method, data, token)
	}
	
};

// 普通请求
function request(path, method, data, token) {
	return new Promise((resolve, reject) => {
		uni.request({
			url : path,
			method : method,
			data : data,
			header : token,
			success(response) {
				console.log('%c'+path+'：', ' background:green', response);
				if (response.data.code === 40101) {
				}
				resolve(response.data);
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});
				console.error('%c响应拦截：', ' background:red', err);
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}

// 文件请求
function uploadFile(path, data, token) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: path,
			filePath: data,
			name: 'file',
			header: token,
			success(res) {
				console.log('上传成功:', res);
			},
			fail(err) {
				console.error('上传失败:', err);
			}
		});
	});
}